package cn.HuanG;

import com.sun.org.apache.xpath.internal.operations.Gte;
import org.apache.logging.log4j.core.config.plugins.util.ResolverUtil;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.delete.DeleteRequestBuilder;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequestBuilder;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.Test;
import org.omg.DynamicAny.DynArray;

import java.awt.dnd.DragGestureEvent;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

/**
 * java操作es对索引库增删改查
 */
public class EsTest {
    /**
     * 配置方法
     * 连接es获取client对象
     * @return
     */
    public TransportClient  getClient(){
        try {
            TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
            return  client;
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
            return null;
    }

    /**
     * 使用java完成es的增删改查
     */
    //增加
    @Test
    public void add(){
        //获取连接
        TransportClient client = getClient();
        //建立建立索引库  类型   id
        IndexRequestBuilder builder = client.prepareIndex("huang", "java", "1");
        //因为es数据存储结构类似于k————v 所以用hashmap来保存
        HashMap<String, Object> data = new HashMap<>();
        data.put("name","qiangqiang");
        data.put("age",18);
        data.put("sex","boy");
        builder.setSource(data);
        IndexResponse response = builder.get();
        System.out.println(response);

    }
    //修改
    @Test
    public void update(){
        //get连接
        TransportClient client = getClient();
        //get修改索引库 类型  id
        UpdateRequestBuilder builder = client.prepareUpdate("huang", "java", "1");
        //hash
        HashMap<String, Object> data = new HashMap<>();
        //把要修改的数据放进map里面
        data.put("age",20);
        //将数据设置进去
        builder.setDoc(data);
        UpdateResponse response = builder.get();
        System.out.println(response);
    }

    //删除
    @Test
    public void delete(){
        //get练级
        TransportClient client = getClient();
        //get删除索引库   id   type类型
        DeleteRequestBuilder builder = client.prepareDelete("huang", "java", "1");
        //删除
        DeleteResponse response = builder.get();
        System.out.println(response);
    }
    //批量增加
    @Test
    public void bulk(){
        //get连接
        TransportClient client = getClient();
        //批量增加  索引库  id   类型
        BulkRequestBuilder bulk = client.prepareBulk();
        //批量操作用for循环
        for(int i=1;i<20;i++){
            // get单个增加索引库  id   类型
            IndexRequestBuilder builder = client.prepareIndex("huang", "java", String.valueOf(i));
            HashMap<String, Object> data = new HashMap<>();
            data.put("age",19+i);
            if ( i%2 == 0){
                data.put("name","小强"+i);
                data.put("hobby","wash");
            }else {
                data.put("name","小吕"+i);
                data.put("hobby","look");
            }
            builder.setSource(data);
            bulk.add(builder);
        }
        bulk.get();
    }
    //查询
    @Test
    public void query(){
        //get连接
        TransportClient client = getClient();
        //查询,获取索引库下面的类型
        SearchRequestBuilder builder = client.prepareSearch("huang").setTypes("java");
        //因为dsl查询里面结构有bool，所以先获取bool
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //因为里面有must，所以获取must，然后在获取里面willter
        boolQuery.must(QueryBuilders.wildcardQuery("name","小**"));
        //bool里面有filter，所以再次获取filter
        boolQuery.filter(QueryBuilders.rangeQuery("age").gte(20));
        builder.setQuery(boolQuery);
        //设置分页
        builder.setSize(5);
        builder.setFrom(0);
        //设置排序
        builder.addSort("age", SortOrder.ASC);
        //get数据
        SearchResponse response = builder.get();
        //hits，里面是所有的数据
        SearchHits hits = response.getHits();
        //使用hits里面封装的迭代器
        Iterator<SearchHit> iterator = hits.iterator();
        while  (iterator.hasNext()){
            SearchHit hit = iterator.next();
            //hit是对象：org.elasticsearch.search.internal.InternalSearchHit@4fcc0416
//            System.out.println(hit);
            //所以需要去对象里面去取数据源
            String sourceAsString = hit.getSourceAsString();
            System.out.println(sourceAsString);

        }
    }
}
